package com.qf.dao.impl;

import com.qf.dao.OrderDao;
import com.qf.entity.Order;
import com.qf.util.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author AzureSky_X
 * @Date 2020/11/19 16:30
 * @Version 1.0
 */
public class OrderDaoImpl implements OrderDao {
    private QueryRunner qr=new QueryRunner();
    @Override
    public void insertOrder(Order order) {
        String sql="insert into tb_order (orderNum,orderSum,orderTime,orderStatus,aid,uid) values (?,?,?,?,?,?)";

        try {
            //自增长id的获取

            /**
             * 原生的
             * autoGeneratedKeys传入1即可拿到回调的值
             * preparStatement的executeQuery拿到的结果集中有回调的值
             *
             * QueryRunner
             */
            ResultSetHandler rs=new ScalarHandler();
            /**
             * insert:回调的自增长id值
             */
            long insert = (long) qr.insert(DbUtils.getConnection(), sql, rs, order.getOrderNum(), order.getOrderSum(), order.getOrderTime(), order.getOrderStatus(), order.getAid(), order.getUid());
            System.out.println(insert);
            order.setId((int) insert);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<Order> selectOrdersByUid(Integer id) {
        String sql="select * from tb_order where uid=?";
        List<Order> query = null;
        try {
            query = qr.query(DbUtils.getConnection(), sql, new BeanListHandler<>(Order.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public Order selectOrdersById(int id) {
        String sql="select * from tb_order where id=?";
        Order query = null;
        try {
            query = qr.query(DbUtils.getConnection(), sql, new BeanHandler<>(Order.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }
}
